package com.chinaunicom.emergency.security;


import com.alibaba.fastjson.JSONObject;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


/**
 * RSA加密解密工具
 * 
 
 */
public class RsaUtil {
    private static String privateKeyStr="MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDSAxnuIgmmXk1St1daZvf/AfWM\n" +
			"jLpU4wSgTpTABzf8ctel4uK5FHEjODJat87JZQVD2GQbS+S7R7gmWLY6cPi138Uxt3IWZERO41qm\n" +
			"G5TV12uDVZUe2/LLC2oR7LaR0fHnU78j6dRkUWcj+nlUxz57VB/gLo3Wo9UzsAT8TogFmsC3iwvM\n" +
			"4Wwa1TzxJGiCLFUdC69q1XvJ/5q3xFWUsso34E+0BG9ADt1vlYmZPMiGNQaIoWNQr8eolQsKEIGv\n" +
			"ff4X6LMo1x1OQknnAMO5CIjgiPPXfV6fO4aYsA5/BUY3ul7Xmg1k4gkbqW+u6FcK3mEDs3gGvLwH\n" +
			"vTuNMeTX9NTTAgMBAAECggEAHwdsRl3rFRSr0gPauTWrgJb2g7yrLy2XmmPh4HlwkTEaoZzjKLtX\n" +
			"d/+umO69c84kOAD50XqmIfGXyLqkuf/FD4IvbYgQKDTKTumSlCZRGENK1E3JyZRvzAY0ts9FrkfZ\n" +
			"uPcLr6+1vNi2J3+ze44wsiIcz4+xTzxHnOpt4iVsPX96YVjVS3wjm/kSKtN1Omth/tFZ+fYgN1N1\n" +
			"WWvcpz+rLdBScBvBeAUYYGh6+C5LSRr1vl1mbUO3TkH1Eg2QQtjL4SctQFKnkx4wLv6Q2zj1fU1M\n" +
			"1D/zzWEfkK9rIpiLXeX4a7fM/5A82QFjEDO6hFpqw/x4l//v4kK7X8lHlcIvyQKBgQDrbhGVBKHE\n" +
			"7Sfffg3nYJZrvXV7+JKPnGB8/qB8DQaFKN40Fp1d8CcrnAS8VwCPdI2RLIAwAXtrASTt4A7KSDRs\n" +
			"jtGOZ2HERJ8tH1GmGkywDdNYRgqr3Esd58hUsTsdPccWxzQI3tUNdB8yuSNAGe2949FlrO3lWqV3\n" +
			"t7c4RQkBFwKBgQDkXIEWbvSsEQbasIN0T9zOvrOojwy/CVSmComOGWQipmElaXkcDUroAt39s8el\n" +
			"IyZP98RUNQ2xwkrGUJAoEl3hU7Xd/oGk68S1Dv6DYsbuoKrsWTGNr788TnoDMhPsXlpvOiNteSSH\n" +
			"S0POJHcNQz5V6ieWqTbFECqf/yDap4yHpQKBgQCQ+a3ACyMm5jdoi/I56iOW4wtGtRJjdxN/xTjE\n" +
			"Sy0ZsMnsX4S2hR1J4ICWDildLZPDsxiY90Ct6v13skLJU99cfjITNBxjRTKUEbYwx/8zZsAfmroV\n" +
			"jMmA9+tII/9YCWPg5fhoAfhGmZxgmttXLOBWz8RxjSTN2J0OdMZR00kxLwKBgQDT3ar6KDkiRq3I\n" +
			"SYm8aLfgrHc8hHN77ek2H4KdbptDtn9c2W0+hGqhtL9GuPwaDvFlsebZhVtON4duVKJaOygUfLi3\n" +
			"3H9lhkQ7A01IkmUkUbYij2H1JT/UcK6stlJbsvJOTW8/CuzEBSVEZPp7OI7l4NeX5ShmTmhthqNx\n" +
			"mY887QKBgQDCZsQ8JG7gYuBdsGgTfHj0uxzGgPuzNub4Dn2BOXOfqFB+Gw8+knuNQVlimaACoi3J\n" +
			"UvZ71LZZRaDouAOOjtaQH+uauVCfK3WgFIbZMZPuhNjHo33wl0EsxulVZdKL70KJM9+5RfVX4XY2\n" +
			"RsvNtoleIbFqT88WMs31bqy7QtKsog==";


    private static String publicKeyStr="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0gMZ7iIJpl5NUrdXWmb3/wH1jIy6VOME\n" +
			"oE6UwAc3/HLXpeLiuRRxIzgyWrfOyWUFQ9hkG0vku0e4Jli2OnD4td/FMbdyFmRETuNaphuU1ddr\n" +
			"g1WVHtvyywtqEey2kdHx51O/I+nUZFFnI/p5VMc+e1Qf4C6N1qPVM7AE/E6IBZrAt4sLzOFsGtU8\n" +
			"8SRogixVHQuvatV7yf+at8RVlLLKN+BPtARvQA7db5WJmTzIhjUGiKFjUK/HqJULChCBr33+F+iz\n" +
			"KNcdTkJJ5wDDuQiI4Ijz131enzuGmLAOfwVGN7pe15oNZOIJG6lvruhXCt5hA7N4Bry8B707jTHk\n" +
			"1/TU0wIDAQAB";

	public static String getPrivateKeyStr() {
		return privateKeyStr;
	}
	public static String getPublicKeyStr() {
		return publicKeyStr;
	}

	/**
     * 随机生成RSA密钥对
     *
     * @param keyLength
     *            密钥长度，范围：512～2048<br>
     *            一般1024
     * @return
     */
    private static KeyPair generateRSAKeyPair(int keyLength)
    {
        try
        {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA",new org.bouncycastle.jce.provider.BouncyCastleProvider());
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (Throwable e)
        {
            e.printStackTrace();
            return null;
        }
    }


	/**
	 * 公钥加密
	 * 
	 * @param key 公钥
	 * @param data 明文
	 * @return <b>String</b> 密文<b><br/>null</b> 加密失败
	 */
	public static String encryptByPublicKey(String key, String data) {
		try {
			RSAPublicKey publicKey = getPublicKey(key);
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			byte[] rsa = cipher.doFinal(data.getBytes());
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(rsa);
		} catch (Exception e) {
		}
		return null;
	}
 
	/**
	 * 私钥解密
	 * 
	 * @param key 私钥
	 * @param data 密文
	 * @return <b>String</b> 明文<b><br/>null</b> 解密失败
	 */
	public static String decryptByPrivateKey(String key, byte[] data) {
		try {
			RSAPrivateKey privateKey = getPrivateKey(key);
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] rsa = cipher.doFinal(data);
			return new String(rsa, "UTF-8");
		} catch (Exception e) {
		}
		return null;
	}
	
	/**
	 * 私钥解密
	 * 
	 * @param key 私钥
	 * @param data 密文
	 * @return <b>String</b> 明文<b><br/>null</b> 解密失败
	 */
	public static String decryptByPrivateKey(String key, String data) {
		try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bdata = decoder.decodeBuffer(data);
			RSAPrivateKey privateKey = getPrivateKey(key);
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.DECRYPT_MODE, privateKey);
			byte[] rsa = cipher.doFinal(bdata);
			return new String(rsa,"UTF-8");
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 公钥解密
	 * 
	 * @param key 公钥
	 * @param data 密文
	 * @return <b>String</b> 明文<b><br/>null</b> 解密失败
	 */
	public static String decryptByPublicKey(String key, byte[] data) {
		try {
			RSAPublicKey publicKey = getPublicKey(key);
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			byte[] rsa = cipher.doFinal(data);
			return new String(rsa, "UTF-8");
		} catch (Exception e) {
		}
		return null;
	}
	

	private static RSAPrivateKey getPrivateKey(String key) {
		try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] keyBytes = decoder.decodeBuffer(key);
			PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory factory = KeyFactory.getInstance("RSA");
			return (RSAPrivateKey) factory.generatePrivate(spec);
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return null;
	}
	
	private static RSAPublicKey getPublicKey(String key) {
		try {
		    BASE64Decoder decoder = new BASE64Decoder();
            byte[] keyBytes = decoder.decodeBuffer(key);
			X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
			KeyFactory factory = KeyFactory.getInstance("RSA");
			return (RSAPublicKey) factory.generatePublic(spec);
		} catch (Exception e) {
		}
		return null;
	}
	
	private static byte[] hexToByte(byte[] hex){
		if(hex.length%2!=0){
			return null;
		}
		byte[] b = new byte[hex.length/2];
		for(int i=0;i<hex.length;i+=2){
			String str = new String(hex, i, 2);
			b[i/2] = (byte) Integer.parseInt(str, 16);
		}
		return b;
	}

	public static void main(String[] args){
	    //生成公私秘钥
//	    KeyPair keyPair = generateRSAKeyPair(1024);
//	    BASE64Encoder encoder = new BASE64Encoder();
//	    System.out.println("公钥："+encoder.encode(keyPair.getPublic().getEncoded()));
//	    System.out.println("私钥："+encoder.encode(keyPair.getPrivate().getEncoded()));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userName","ADMIN");
        jsonObject.put("password","123456");
//		jsonObject.put("oldPassword","123456");
//		jsonObject.put("newPassword","121212");
        jsonObject.put("code","");
        jsonObject.put("tid","a7e1ee6f40d6502fabf4878fa0ea2584");
        String message = jsonObject.toJSONString();

        String content = encryptByPublicKey(publicKeyStr,message);
        System.out.println(content);
	    System.out.println(decryptByPrivateKey(RsaUtil.privateKeyStr,"TXn6wPlHqzRqCJB/z87yuHkwyIxc6wT+qtwboGK+sGA0yy30gyMlCcxbUncOF3F3DwCjwkKx/rKP\n" +
				"VzuVG7JUTvvt5R0McfHuf9R9cF3VqWIXngXS3Q7ZYva0NkrHVeQ6Xzw4Avo47ZNv+oeyit2r0d5F\n" +
				"8CV4oKwLGij/wHxDdmvJKjA01+ya212lWr5o3wYY590QrwpytvIESbkS2uD5/6/37qLIHOCKR8Zv\n" +
				"MTbaYPlhk9Pr/Y7+NYpzV2l3mK+lJ9rvJE842WtrhZ4ebZASnFeFZtTDtKGrRUj4feTemfAOl/tk\n" +
				"MuhuO3Xu25NMzItNOf4v/vL6jJ7D7Nfe60XOvA=="));

	    //生成公私密钥对
		KeyPair keyPair = generateRSAKeyPair(2048);
		Key publicKey = keyPair.getPublic();
		Key privateKey = keyPair.getPrivate();
		byte[] publicKeyBytes = publicKey.getEncoded();
		byte[] privateKeyBytes = privateKey.getEncoded();
		String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);
		String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);
		System.out.println("==========public==========");
		System.out.println(publicKeyBase64);
		System.out.println("==========private==========");
	    System.out.println(privateKeyBase64);
    }

}
